package com.software.loginregister.activity;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;


import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;


import com.google.android.material.button.MaterialButton;
import com.software.loginregister.R;
import com.software.loginregister.api.AiServiceApi;
import com.software.loginregister.util.ClickUtils;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class PhotoConfirmActivity extends AppCompatActivity {

    private ImageView photoImageView;
    private MaterialButton confirmButton;
    private MaterialButton cancelButton;
    private Bitmap photoBitmap;
    private boolean isProcessing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_confirm);

        // 初始化视图
        photoImageView = findViewById(R.id.photo_image_view);
        confirmButton = findViewById(R.id.confirm_button);
        cancelButton = findViewById(R.id.cancel_button);

        // 获取并显示图片
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.containsKey("photo_data")) {
            byte[] byteArray = extras.getByteArray("photo_data");
            photoBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            photoImageView.setImageBitmap(photoBitmap);
        }

        // 设置按钮点击事件
        confirmButton.setOnClickListener(v -> {
            // 检查是否快速点击
            if (ClickUtils.isFastClick()) {
                return;
            }

            // 检查是否正在处理
            if (isProcessing) {
                Toast.makeText(this, "正在处理中，请稍候...", Toast.LENGTH_SHORT).show();
                return;
            }

            // 开始处理
            isProcessing = true;
            confirmButton.setEnabled(false);

            // 显示加载提示
            showLoadingDialog();

            processConfirmedImage();
        });

        cancelButton.setOnClickListener(v -> finish());
        setStatusBar();
    }

    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private void processConfirmedImage() {
        if (photoBitmap != null) {
            try {
                // 将Bitmap转为File
                File imageFile = bitmapToFile(photoBitmap);

                // 创建文件的MultipartBody.Part
                RequestBody requestFile = RequestBody.create(
                        MediaType.parse("image/*"),
                        imageFile
                );
                MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                        "file",
                        imageFile.getName(),
                        requestFile
                );


                Long userId = (long) SharedPreferencesUtil.getUserId(this);
                if (userId == null) {
                    Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 创建用户ID的RequestBody
                RequestBody userIdBody = RequestBody.create(
                        MediaType.parse("text/plain"),
                        String.valueOf(userId)// 替换为实际的用户ID
                );

                // 获取Retrofit服务实例
                AiServiceApi aiService = RetrofitClient.getInstance().create(AiServiceApi.class);

                // 调用上传接口
                aiService.uploadImage(filePart, userIdBody)
                        .enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                isProcessing = false;
                                confirmButton.setEnabled(true);
                                dismissLoadingDialog();
                                if (response.isSuccessful()) {
                                    try {
                                        String result = response.body().string();
                                        Log.d("PhotoConfirmDebug", result);

                                        JSONObject jsonObject = new JSONObject(result);
                                        // 先获取 dify 对象，然后从中获取 id
                                        JSONObject difyObject = jsonObject.getJSONObject("dify");
                                        String uploadFileId = difyObject.getString("id");
                                        String photoUrl = jsonObject.getString("photoUrl");
                                        String imageId = jsonObject.getString("imageId");
                                        Log.d("PhotoConfirmDebug", photoUrl);
                                        // 显示提示
                                        Toast.makeText(PhotoConfirmActivity.this,
                                                "上传成功",
                                                Toast.LENGTH_SHORT).show();

                                        // 创建Intent并跳转
                                        Intent intent = new Intent(PhotoConfirmActivity.this, ResultActivity.class);
                                        intent.putExtra("uploadFileId", uploadFileId);
                                        intent.putExtra("imageId", imageId);
                                        startActivity(intent);

                                        // 发送广播通知FridgeFragment刷新
                                        Intent refreshIntent = new Intent("com.software.loginregister.REFRESH_FRIDGE");
                                        refreshIntent.putExtra("imageId", imageId);

                                        // 使用 LocalBroadcastManager 发送广播
                                        LocalBroadcastManager.getInstance(PhotoConfirmActivity.this).sendBroadcast(refreshIntent);
                                        Log.d("PhotoConfirmDebug", "已通过 LocalBroadcastManager 发送广播");
                                        // 显示提示
                                        Toast.makeText(PhotoConfirmActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                        finish();

                                    } catch (JSONException e) {
                                        Log.d("PhotoConfirmDebug", "JSON解析失败", e);
                                        Toast.makeText(PhotoConfirmActivity.this,
                                                "解析响应失败",
                                                Toast.LENGTH_SHORT).show();
                                    } catch (IOException e) {
                                        Log.d("PhotoConfirmDebug", "IO异常", e);
                                        Toast.makeText(PhotoConfirmActivity.this,
                                                "处理响应失败",
                                                Toast.LENGTH_SHORT).show();
                                        handleError(e);
                                    }
                                } else {
                                    Toast.makeText(PhotoConfirmActivity.this,
                                            "上传失败: " + response.code(),
                                            Toast.LENGTH_SHORT).show();
                                    handleError(new Exception("上传失败: " + response.code()));
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                isProcessing = false;
                                confirmButton.setEnabled(true);  // 重新启用按钮
                                Toast.makeText(PhotoConfirmActivity.this,
                                        "上传失败: " + t.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        });

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this,
                        "处理图片失败: " + e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    // Bitmap转File的辅助方法
    private File bitmapToFile(Bitmap bitmap) throws IOException {
        // 创建文件
        File file = new File(getCacheDir(), "temp_image_" + System.currentTimeMillis() + ".jpg");

        // 将Bitmap写入文件
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            return file;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void handleError(Throwable t) {
        Toast.makeText(this,
                "上传失败: " + t.getMessage(),
                Toast.LENGTH_SHORT).show();
    }

    private ProgressDialog loadingDialog;

    private void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new ProgressDialog(this);
            loadingDialog.setMessage("正在上传...");
            loadingDialog.setCancelable(false);
        }
        loadingDialog.show();
    }

    private void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }
}